<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.4);
            /* margin: 100px; */
            /* transform: translate(); */
            /* position: absolute; */

            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="shadow"></div>
</body>
<script>
    // 盒子跟随鼠标移动?
    // (1)  盒子怎么移动?   => 定位(absolute,fixed 脱离文档流 不会影响其他元素) 
    // (2)  盒子跟随鼠标移动在哪里移动?   文档任意位置
    // (3)  如何知道鼠标当前的位置   => 借助事件对象

    var shadow = document.getElementsByClassName("shadow")[0];

    var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

    var maxLeft = clientWidth - shadow.clientWidth;
    var maxTop = clientHeight - shadow.clientHeight;

    window.onresize = function(){
        clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
        clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

        maxLeft = clientWidth - shadow.clientWidth;
        maxTop = clientHeight - shadow.clientHeight;
    }

    document.onmousemove = function (evt) {
        var evt = evt || window.event;
        var x = evt.pageX - shadow.clientWidth / 2;
        var y = evt.pageY - shadow.clientHeight / 2;
        console.log(x, y);

        if (x <= 0) x = 0;
        if (x >= maxLeft) x = maxLeft;
        if (y <= 0) y = 0;
        if (y >= maxTop) y = maxTop;


        // 取值时记得去单位  赋值时记得加单位
        shadow.style.left = x + "px";
        shadow.style.top = y + "px";
    }



</script>

</html>